package com.project.personalfundmanager.server;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mailer
{
	Properties smtpProperties;

	public Mailer( String userName, String password, String smtpHost, String smtpPort )
	{
	}
	
	public Mailer()
	{
		this( "taxcalci@gmail.com", "taxcalculator", "smtp.gmail.com", "587" );
	}

	public void sendMail( List<String> toAddresses, String subject, String body, MailerCallback callback )
	{
		sendMail( toAddresses, null, subject, body, null, callback );
	}

	public void sendMail( List<String> toAddresses, String subject, String body, List<String> attachments, MailerCallback callback )
	{
		sendMail( toAddresses, null, subject, body, attachments, callback );
	}

	public void sendMail( List<String> toAddresses, List<String> ccAddresses, String subject, String body, List<String> attachments, final MailerCallback callback )
	{
		if ( !hasAddresses( toAddresses ) && !hasAddresses( ccAddresses ) )
			return;

		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("paras.dattani@gmail.com", "Facebook Tax Manager"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(toAddresses.get(0)));
            msg.setSubject(subject);
            msg.setSentDate(new Date());
            msg.setText(body);
            Transport.send(msg);

        } catch (Exception e) {
        	e.printStackTrace();
        }
	}

	private boolean hasAddresses( List<String> addresses )
	{
		if ( addresses == null )
			return false;

		for ( String address : addresses )
		{
			if ( address != null && address != "" )
				return true;
		}

		return false;
	}
}

class MailAuthenticator extends Authenticator
{
	private String username;
	private String password;

	public MailAuthenticator( Properties properties )
	{
		this.username = properties.getProperty( "mail.smtp.user" );
		this.password = properties.getProperty( "mail.smtp.password" );
	}

	public PasswordAuthentication getPasswordAuthentication()
	{
		return new PasswordAuthentication( username, password );
	}
}
